﻿using Nemerle.Collections;
using Nemerle.Text;
using Nemerle.Utility;
using Nemerle.Compiler;

using System;
using System.Collections.Generic;
using System.Linq;

using PT = Nemerle.Compiler.Parsetree;

[assembly: Nemerle.Internal.RegisterParser("Nemerle2.Parser.MacroParserPlugin", ".n2")]

namespace Nemerle2.Parser
{
  /// <summary>
  /// Description of MacroParserPlugin.
  /// </summary>
  [Record]
  public class MacroParserPlugin : IParser
  {
    manager : ManagerClass;

    public Parse(fileIndex : int, code : string) : list[PT.TopDeclaration]
    {
      def fileName = Location.GetFileName(fileIndex);
      def source = Nemerle.Peg.SourceSnapshot(code, fileIndex, fileName);

      def locationConverter = LocationConverter.Default;
      def project = Nemerle2.Compiler.NProject(null);
      def parser = MacroParser(project);
      match(parser.Parse(source))
      {
        | Some(unit) =>
          def converter = AstConverter(manager);
          converter.Convert(unit, locationConverter)

        | _ =>
          def (errorPos, _) = parser.GetMaxRollbackPosAndIds();
          def loc = Nemerle.Peg.Location(source, errorPos, errorPos);
          Message.FatalError(locationConverter.Convert(loc), $"failed to parse file `$fileName'.")
      }
    }
  }
}
